import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { user } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(user)
    private readonly userRepository: Repository<user>,
  ) {}
  // 新建用户
  async create(createUserDto: CreateUserDto) {
    const hasUser = await this.checkUser(createUserDto);
    if (hasUser) {
      return this.checkUser(createUserDto);
    }
    const newuser = new user();
    newuser.username = createUserDto.username;
    newuser.password = createUserDto.password;

    const body = await this.userRepository.save(newuser);
    return { body };
  }
  // 获取所有用户，支持用户名模糊搜索
  async getUserList(query) {
    const queryWrapper = {
      where: {
        username: Like(`%${query?.searchContent || ''}%`),
      },
      skip: query.pageSize * (query.pageNo - 1),
      take: query.pageSize,
    };
    const list = await this.userRepository.find(queryWrapper);
    const total = await this.userRepository.count(queryWrapper);
    return { body: { list, total } };
  }

  // 通过用户名获取用户
  async findOneByUserName(username) {
    const queryWrapper = {
      where: {
        username,
      },
    };
    const list = await this.userRepository.find(queryWrapper);
    return list;
  }

  // 修改用户
  async update(id: number, updateUserDto: UpdateUserDto) {
    // const result = await this.userRepository.update(id, updateUserDto);
    return { body: this.userRepository.update(id, updateUserDto) };
  }

  // 删除用户
  remove(id: number) {
    return { body: this.userRepository.delete(id) };
  }

  // 检查用户是否存在
  async checkUser(createUserDto) {
    const queryWrapper = {
      where: {
        username: createUserDto.username,
      },
    };
    const list = await this.userRepository.find(queryWrapper);
    if (list.length > 0) {
      // throw new Error('用户名已存在');
      return { message: '用户名已存在', code: '000' };
    } else {
      return false;
    }
  }
}
